package com.feel.modules.security.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import com.feel.common.constant.HttpStatus;
import com.feel.common.exception.AuthException;
import com.feel.common.utils.R;
import com.feel.config.PwdConfig;
import com.feel.modules.security.PwdEncoder;
import org.apache.commons.lang3.StringUtils;

public class SimplePwdEncoder implements PwdEncoder {

    private PwdConfig pwd;

    public SimplePwdEncoder(PwdConfig pwd){
        this.pwd = pwd;
    }

    @Override
    public String encode(String password) {
        if(null == pwd || StringUtils.isAnyBlank(pwd.getPublicKey(),pwd.getPrivateKey())){
            throw new AuthException(new R(HttpStatus.UNAUTHORIZED));
        }
        return SaSecureUtil.rsaEncryptByPublic(pwd.getPublicKey(),password);
    }

    @Override
    public String decode(String encodePassword) {
        if(null == pwd || StringUtils.isAnyBlank(pwd.getPublicKey(),pwd.getPrivateKey())){
            throw new AuthException(new R(HttpStatus.UNAUTHORIZED));
        }
        return SaSecureUtil.rsaDecryptByPrivate(pwd.getPrivateKey(),encodePassword);
    }

    @Override
    public boolean match(String password, String encodePassword) {
        return decode(encodePassword).equals(password);
    }
}
